package com.cy.aircompressor.main.home.other;

import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cy.aircompressor.databinding.DialogAlarmThresholdLayoutBinding;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.warning.WarningConfig;
import com.cy.aircompressor.main.home.other.provider.WarningConfigProvider;
import com.cy.aircompressor.main.ui.other.viewmodel.OtherViewModel;
import com.cy.aircompressor.main.view.PageTurningIndicator;
import com.cy.aircompressor.main.view.pop.AirDropdownPopupWindow;
import com.drug.lib.util.ToastUtil;
import com.drug.lib.view.recycptr.DynamicAdpTypePool;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.bean.RowEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMDialogFragment;
import com.net.model.utils.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class AlarmThresholdFragment extends BaseVMDialogFragment<DialogAlarmThresholdLayoutBinding, OtherViewModel> {

    private String[] model = {"HMWS-TC7", "111-TC7"};
    private String compressorModel;

    public static void showDialogFragment(FragmentManager fragmentManager, String tag) {
        Bundle args = new Bundle();
        AlarmThresholdFragment fragment = new AlarmThresholdFragment();
        fragment.setArguments(args);
        fragment.show(fragmentManager, tag);
    }

    @Override
    protected void dataChange() {
        mViewModel.getQueryWarningConfigByPage().observe(this, new Observer<Resource<RowEntity<WarningConfig>>>() {
            @Override
            public void onChanged(Resource<RowEntity<WarningConfig>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<WarningConfig>>() {
                    @Override
                    public void onSuccess(RowEntity<WarningConfig> data) {
                        mBinding.indicator.setRecordTotal(data.getTotal());
                        modelDescRecyclerAdapter.setItems(data.getList());
                        modelDescRecyclerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Integer code, String message) {
                        super.onFailure(code, message);
                        if (code == Constant.EMPTY_DATA_ERROR) {
                            ToastUtil.show("未找到配置信息详情");
                            modelDescRecyclerAdapter.setItems(new ArrayList<>());
                            modelDescRecyclerAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        });
        mViewModel.getBatchUpdateWarningConfig().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        ToastUtil.show("修改成功");
                        requestNetwork();
                    }
                });
            }
        });
    }

    @Override
    protected DialogAlarmThresholdLayoutBinding getViewBinding() {
        return DialogAlarmThresholdLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        initView();
        initModelDescRecycler();
    }

    @Override
    protected void requestNetwork() {
        mViewModel.queryWarningConfigByPage(pageNum, pageSize, compressorModel);
    }


    @Override
    protected int getWindowWidth() {
        return getScreenWidth()*2/3;
    }


    DynamicRecyclerAdapter modelDescRecyclerAdapter;

    private void initModelDescRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.modelDesc.setLayoutManager(mLayoutManager);
        modelDescRecyclerAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        WarningConfigProvider warningConfigProvider = new WarningConfigProvider(mContext);
        pool.register(WarningConfig.class, warningConfigProvider);
        modelDescRecyclerAdapter.registerAll(pool);
        mBinding.modelDesc.setAdapter(modelDescRecyclerAdapter);
    }

    private Integer pageNum = 1;
    private Integer pageSize = 10;


    private void initView() {
        RxView.clicks(mBinding.negative)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    dismiss();
                });
        RxView.clicks(mBinding.closeBtn)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    dismiss();
                });
        RxView.clicks(mBinding.positive)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    List<WarningConfig> configList = modelDescRecyclerAdapter.getItems();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        List<WarningConfig> warningConfigs = configList.stream().filter(new Predicate<WarningConfig>() {
                            @Override
                            public boolean test(WarningConfig warningConfig) {
                                return warningConfig.isSelect();
                            }
                        }).collect(Collectors.toList());
                        if (warningConfigs != null && warningConfigs.size() > 0) {
                            List<Object> parameters = new ArrayList<>();
                            warningConfigs.forEach(new Consumer<WarningConfig>() {
                                @Override
                                public void accept(WarningConfig warningConfig) {
                                    try {
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("compressorModel", warningConfig.getCompressorModel());
                                        jsonObject.put("compressorPartCode", warningConfig.getCompressorPartCode());
                                        jsonObject.put("compressorPointCode", warningConfig.getCompressorPointCode());
                                        jsonObject.put("id", warningConfig.getId());
                                        jsonObject.put("maxValue", warningConfig.getMaxValue());
                                        jsonObject.put("minValue", warningConfig.getMinValue());
                                        jsonObject.put("sensorType", warningConfig.getSensorType());
                                        jsonObject.put("status", warningConfig.getStatus());
                                        jsonObject.put("triggerCount", warningConfig.getTriggerCount());
                                        parameters.add(jsonObject);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            mViewModel.batchUpdateWarningConfig(parameters);
                        }
                    }


                });
        mBinding.indicator.setPageNum(pageNum);
        mBinding.indicator.setPageSize(pageSize);
        mBinding.indicator.setEnableSize(false);

        mBinding.indicator.setPageTurningIndicatorCallBack(new PageTurningIndicator.PageTurningIndicatorCallBack() {
            @Override
            public void skipPage(int pageNum) {
                AlarmThresholdFragment.this.pageNum = pageNum;
                requestNetwork();
            }

            @Override
            public void pageSize(int size) {
                AlarmThresholdFragment.this.pageSize = size;
                requestNetwork();
            }
        });

        List<SelectDict> selectDicts = new ArrayList<>();
        Arrays.asList(model).forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                SelectDict selectDict = new SelectDict();
                selectDict.setLabel(s);
                selectDicts.add(selectDict);
            }
        });
        compressorModel = selectDicts.get(0).getLabel();
        RxView.clicks(mBinding.selectedConfig)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    AirDropdownPopupWindow mPopupWindow = new AirDropdownPopupWindow(mContext, mBinding.selectedConfig, mBinding.selectedConfig, selectDicts);
                    mPopupWindow.setDropdownCallBack(new AirDropdownPopupWindow.DropdownCallBack() {
                        @Override
                        public void select(SelectDict selectDict) {
                            compressorModel = selectDict.getLabel();
                            requestNetwork();
                        }
                    });
                    mPopupWindow.showAsDropDown(mBinding.selectedConfig);//显示PopupWindow小弹窗
                });
    }
}
